/*
 * Copyright (c) 2024.  little3201.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *       https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.server.starter.exploiter.controller;

import com.server.starter.exploiter.domain.ColumnInfo;
import com.server.starter.exploiter.domain.TableInfo;
import com.server.starter.exploiter.service.DBService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/db")
public class DBController {

    private static final Logger logger = LoggerFactory.getLogger(DBController.class);

    private final DBService dbService;

    public DBController(DBService dbService) {
        this.dbService = dbService;
    }

    /**
     * 根据所有表
     *
     * @return 查询的数据，异常时返回204状态码
     */
    @GetMapping("/tables")
    public ResponseEntity<List<TableInfo>> tables() {
        List<TableInfo> list;
        try {
            list = dbService.findAllTables();
        } catch (Exception e) {
            logger.error("Retrieve table occurred an error: ", e);
            return ResponseEntity.noContent().build();
        }
        return ResponseEntity.ok(list);
    }

    /**
     * 根据 tableName 查询
     *
     * @param tableName table name
     * @return 查询的数据，异常时返回204状态码
     */
    @GetMapping("/{tableName}/columns")
    public ResponseEntity<List<ColumnInfo>> columns(@PathVariable String tableName) {
        List<ColumnInfo> list;
        try {
            list = dbService.findAllColumnsByTableName(tableName);
        } catch (Exception e) {
            logger.error("Fetch table columns occurred an error: ", e);
            return ResponseEntity.noContent().build();
        }
        return ResponseEntity.ok(list);
    }
}
